#include "DS1302.h"

sbit DS1302_SCK = P4 ^ 3;
sbit DS1302_SDA = P4 ^ 2;
sbit DS1302_RST = P4 ^ 1;

void Write_Ds1302(unsigned char temp);
void Write_Ds1302_Byte(unsigned char DS1302_address, unsigned char DS1302_data);
unsigned char Read_Ds1302_Byte(unsigned char DS1302_address);
void Rtc_Init(unsigned char* ucRtc);
void Read_Rtc(unsigned char* ucRtc);

/**
 * @brief write DS1302
 * 
 * @param temp write DS1302_address and DS1302_date
 */
void Write_Ds1302(unsigned char temp)
{
	unsigned char i;
	for (i = 0; i < 8; i++)
	{
		DS1302_SCK = 0;
		DS1302_SDA = temp & 0x01;
		temp >>= 1;
		DS1302_SCK = 1;
	}
}

/**
 * @brief write DS1302 byte
 * 
 * @param DS1302_address 
 * @param DS1302_data
 */
void Write_Ds1302_Byte(unsigned char DS1302_address, unsigned char DS1302_data)
{
	DS1302_RST = 0;
	_nop_();
	DS1302_SCK = 0;
	_nop_();
	DS1302_RST = 1;
	_nop_();
	Write_Ds1302(DS1302_address);
	Write_Ds1302(DS1302_data);
	DS1302_RST = 0;
}

/**
 * @brief read DS1302 byte
 * 
 * @param DS1302_address 
 * @return unsigned char 
 */
unsigned char Read_Ds1302_Byte(unsigned char DS1302_address)
{
	unsigned char i, temp = 0x00;
	DS1302_RST = 0;
	_nop_();
	DS1302_SCK = 0;
	_nop_();
	DS1302_RST = 1;
	_nop_();
	Write_Ds1302(DS1302_address);
	for (i = 0; i < 8; i++)
	{
		DS1302_SCK = 0;
		temp >>= 1;
		if (DS1302_SDA)
			temp |= 0x80;
		DS1302_SCK = 1;
	}
	DS1302_RST = 0;
	_nop_();
	DS1302_SCK = 0;
	_nop_();
	DS1302_SCK = 1;
	_nop_();
	DS1302_SDA = 0;
	_nop_();
	DS1302_SDA = 1;
	_nop_();
	return temp;
}

/**
 * @brief rtc init
 * 
 * @param ucRtc 
 */
void Rtc_Init(unsigned char* ucRtc)
{
	unsigned char i = 0;
	Write_Ds1302_Byte(0x8e,0x00);
	for(i = 0; i < 5; i++)
	{
		Write_Ds1302_Byte(0x88-2*i,ucRtc[i]);
	}
		Write_Ds1302_Byte(0x8e,0x00);
}

/**
 * @brief read rtc
 * 
 * @param ucRtc 
 */
void Read_Rtc(unsigned char* ucRtc)
{
	unsigned char i;
	for(i = 0; i < 5; i++)
	{
		ucRtc[i]=Read_Ds1302_Byte(0x89-2*i);
	}
}